// import 'package:emoji_picker_flutter/emoji_picker_flutter.dart';
// import 'package:flutter/foundation.dart' as foundation;
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:image_picker/image_picker.dart';
import 'package:node_chat/CustomUI/OwnFileCard.dart';
import 'package:node_chat/CustomUI/ReplyFileCard.dart';
import 'package:node_chat/Model/ChatModel.dart';
import 'package:node_chat/screen/CameraScreen.dart';
import 'package:node_chat/screen/CameraViewPage.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:http/http.dart' as http;

import '../CustomUI/OwnMessgaeCrad.dart';
import '../CustomUI/ReplyCard.dart';
import '../Model/MessageModel.dart';

class Inividualpage extends StatefulWidget {
  const Inividualpage(
      {super.key, required this.chatModel, required this.sourchat});

  final ChatModel chatModel;
  final ChatModel sourchat;

  @override
  State<Inividualpage> createState() => _InividualpageState();
}

class _InividualpageState extends State<Inividualpage> {
  final TextEditingController _controller = TextEditingController();

  FocusNode focusNode = FocusNode();
  final ScrollController _scrollController = ScrollController();
  late WebSocketChannel channel;
  final ImagePicker _picker = ImagePicker();

  late XFile? file;

  int popTime = 0;

  bool sendButton = false;
  List<MessageModel> messages = [];

  // _onBackspacePressed() {
  //   _controller
  //     ..text = _controller.text.characters.toString()
  //     ..selection = TextSelection.fromPosition(
  //         TextPosition(offset: _controller.text.length));
  // }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    connectToWebSocket();
    sendSignIn('signin', widget.sourchat.id.toString());
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    channel.sink.close();
  }

  //连接登录
  void sendSignIn(String channelType, String clientId) {
    final message = jsonEncode({
      'type': channelType,
      'payload': {'id': clientId},
    });
    channel.sink.add(message);
  }

  //发送消息
  void sendMessage(
      String targetId, String senderId, String content, String path) {
    print("发送消息");
    print(targetId);
    print(senderId);
    print(content);
    // setMessage("source", content, path);
    final messageData = {
      'type': 'message',
      'payload': {
        'targetId': targetId,
        'senderId': senderId,
        'content': content,
        'path': path,
      },
    };
    final message = jsonEncode(messageData);
    channel.sink.add(message);
  }

  //添加消息
  void setMessage(String type, String message, String path) {
    MessageModel messageModel = MessageModel(
        type: type,
        message: message,
        time: DateTime.now().toString().substring(10, 16),
        path: path);
    print(messages);

    setState(() {
      messages.add(messageModel);
    });
  }

  //发送图片到服务器
  void OnImageSend(String path, String message) async {
    print("here is path $path");

    for (int i = 0; i < popTime; i++) {
      Navigator.pop(context);
    }
    setState(() {
      popTime = 0;
    });
    var request = http.MultipartRequest(
        "POST", Uri.parse("http://127.0.0.1:6000/routes/addimage"));
    request.files.add(await http.MultipartFile.fromPath("img", path));
    request.headers.addAll({
      "Content-Type": "application/form-data",
    });
    http.StreamedResponse response = await request.send();
    var httpResponse = await http.Response.fromStream(response);
    var data = jsonDecode(httpResponse.body);
    print(data['path']);
    setMessage("source", message, path);

    sendMessage(widget.chatModel.id.toString(), widget.sourchat.id.toString(),
        message, data['path']);
  }

  void connectToWebSocket() {
    channel = WebSocketChannel.connect(
      Uri.parse('ws://127.0.0.1:6000'),
    );

    // 在此处可以执行与连接建立相关的操作，例如发送初始握手消息等
    // ...

    // 监听 WebSocket 连接的状态变化
    channel.stream.listen(
      (event) {
        // 处理收到的消息
        handleWebSocketMessage(event);
      },
      onError: (error) {
        // 处理错误
        handleError(error);
      },
      onDone: () {
        // 处理连接关闭
        handleConnectionClosed();
      },
    );
  }

  void handleWebSocketMessage(String message) {
    // 处理收到的消息
    print('Received message: $message');
    final jsonData = jsonDecode(message);
    final content = jsonData['payload']['content'];
    final path = jsonData['payload']['path'];
    setMessage("destination", content, path);
  }

  void handleError(dynamic error) {
    // 处理错误
    print('WebSocket error: $error');
  }

  void handleConnectionClosed() {
    // 处理连接关闭
    print('WebSocket connection closed');
    channel.sink.close();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(children: [
      Image.asset(
        "assets/whatsapp_Back.png",
        height: MediaQuery.of(context).size.height,
        width: MediaQuery.of(context).size.width,
        fit: BoxFit.cover,
      ),
      Scaffold(
        backgroundColor: Colors.transparent,
        appBar: PreferredSize(
          preferredSize: const Size.fromHeight(60),
          child: AppBar(
            leadingWidth: 70,
            titleSpacing: 0,
            leading: InkWell(
              onTap: () {
                Navigator.pop(context);
              },
              child: Row(
                children: [
                  const Icon(
                    Icons.arrow_back,
                    size: 24,
                  ),
                  CircleAvatar(
                    radius: 20,
                    backgroundColor: Colors.blueGrey,
                    child: SvgPicture.asset(
                      widget.chatModel.isGroup
                          ? "assets/groups.svg"
                          : "assets/person.svg",
                      height: 38,
                      width: 38,
                    ),
                  ),
                ],
              ),
            ),
            title: InkWell(
              onTap: () {},
              child: Container(
                margin: const EdgeInsets.all(5),
                child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        widget.chatModel.name,
                        style: const TextStyle(
                            fontSize: 18.5, fontWeight: FontWeight.bold),
                      ),
                      const Text(
                        "last seen today at 12:05",
                        style: TextStyle(fontSize: 13),
                      )
                    ]),
              ),
            ),
            actions: [
              IconButton(
                icon: const Icon(Icons.videocam),
                onPressed: () {},
              ),
              IconButton(
                icon: const Icon(Icons.call),
                onPressed: () {},
              ),
              PopupMenuButton<String>(
                onSelected: (value) {
                  print(value);
                },
                itemBuilder: (BuildContext conttext) {
                  return [
                    const PopupMenuItem(
                      value: "View Contact",
                      child: Text("View Contact"),
                    ),
                    const PopupMenuItem(
                      value: "Media,link,and doc",
                      child: Text("Media,link,and doc"),
                    ),
                    const PopupMenuItem(
                      value: "whatsapp web",
                      child: Text("whatsapp web"),
                    ),
                    const PopupMenuItem(
                      value: "search",
                      child: Text("serach"),
                    ),
                    const PopupMenuItem(
                      value: "Mute Notification",
                      child: Text("Mute Notification"),
                    ),
                    const PopupMenuItem(
                      value: "Wallpaper",
                      child: Text("Wallpaper"),
                    ),
                  ];
                },
              )
            ],
          ),
        ),
        body: SizedBox(
          height: MediaQuery.of(context).size.height,
          width: MediaQuery.of(context).size.width,
          child: Column(
            children: [
              Expanded(
                // height: MediaQuery.of(context).size.height - 150,
                child: ListView.builder(
                  shrinkWrap: true,
                  controller: _scrollController,
                  itemCount: messages.length + 1,
                  itemBuilder: (context, index) {
                    if (index == messages.length) {
                      return Container(
                        height: 70,
                      );
                    }
                    if (messages[index].type == "source") {
                      if (messages[index].path.isNotEmpty) {
                        return OwnFileCard(
                          path: messages[index].path,
                          message: messages[index].message,
                          time: messages[index].time,
                        );
                      } else {
                        return OwnMessageCard(
                          message: messages[index].message,
                          time: messages[index].time,
                        );
                      }
                    } else {
                      if (messages[index].path.isNotEmpty) {
                        return ReplyFileCard(
                          path: messages[index].path,
                          message: messages[index].message,
                          time: messages[index].time,
                        );
                      } else {
                        return ReplyCard(
                            message: messages[index].message,
                            time: messages[index].time);
                      }
                    }
                  },
                ),
                // child: ListView(
                //   children: const [
                //     OwnFileCard(
                //       path: '',
                //     ),
                //     ReplyFileCard()
                //   ],
                // ),
              ),
              Align(
                alignment: Alignment.bottomCenter,
                child: SizedBox(
                  height: 70,
                  child: Row(
                    children: [
                      SizedBox(
                        width: MediaQuery.of(context).size.width - 55,
                        child: Card(
                          margin: const EdgeInsets.only(
                              left: 2, right: 2, bottom: 8),
                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(25)),
                          child: TextFormField(
                            controller: _controller,
                            focusNode: focusNode,
                            textAlignVertical: TextAlignVertical.center,
                            keyboardType: TextInputType.multiline,
                            maxLines: 5,
                            minLines: 1,
                            onChanged: (value) {
                              if (value.isNotEmpty) {
                                setState(() {
                                  sendButton = true;
                                });
                              } else {
                                setState(() {
                                  sendButton = false;
                                });
                              }
                            },
                            decoration: InputDecoration(
                                border: InputBorder.none,
                                hintText: "Type  a message",
                                prefixIcon: IconButton(
                                  icon: const Icon(Icons.emoji_emotions),
                                  onPressed: () {},
                                ),
                                suffixIcon: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    IconButton(
                                        icon: const Icon(Icons.attach_file),
                                        onPressed: () {
                                          showModalBottomSheet(
                                              backgroundColor:
                                                  Colors.transparent,
                                              context: context,
                                              builder: (builder) =>
                                                  bottomSheet());
                                        }),
                                    IconButton(
                                        icon: const Icon(Icons.camera_alt),
                                        onPressed: () {
                                          setState(() {
                                            popTime = 2;
                                          });
                                        })
                                  ],
                                ),
                                contentPadding: const EdgeInsets.all(5)),
                          ),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.only(
                            bottom: 8.0, right: 3, left: 2),
                        child: CircleAvatar(
                          radius: 25,
                          backgroundColor: const Color(0xFF128C7E),
                          child: IconButton(
                              icon: Icon(
                                sendButton ? Icons.send : Icons.mic,
                                color: Colors.white,
                              ),
                              onPressed: () {
                                if (sendButton) {
                                  _scrollController.animateTo(
                                      _scrollController
                                          .position.maxScrollExtent,
                                      duration:
                                          const Duration(milliseconds: 300),
                                      curve: Curves.easeOut);
                                  sendMessage(
                                      widget.chatModel.id.toString(),
                                      widget.sourchat.id.toString(),
                                      _controller.text,
                                      "");
                                }
                                _controller.clear();
                                setState(() {
                                  sendButton = false;
                                });
                              }),
                        ),
                      )
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    ]);
  }

  Widget bottomSheet() {
    return SizedBox(
      height: 278,
      width: MediaQuery.of(context).size.width,
      child: Card(
        margin: const EdgeInsets.symmetric(horizontal: 10, vertical: 20),
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                iconcreation(
                    Icons.insert_drive_file, Colors.indigo, "Document", () {}),
                const SizedBox(
                  width: 40,
                ),
                iconcreation(Icons.camera_alt, Colors.pink, "Camera", () {
                  setState(() {
                    popTime = 3;
                  });
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (build) => CameraScreen(
                              OnImageSend: OnImageSend,
                            )),
                  );
                }),
                const SizedBox(
                  width: 40,
                ),
                iconcreation(Icons.insert_photo, Colors.purple, "Gallery",
                    () async {
                  setState(() {
                    popTime = 2;
                  });
                  file = await _picker.pickImage(source: ImageSource.gallery);
                  print(file?.path);
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (build) => CameraViewPage(
                              path: file!.path,
                              onImgSend: OnImageSend,
                            )),
                  );
                }),
              ],
            ),
            const SizedBox(
              height: 30,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                iconcreation(Icons.headset, Colors.indigo, "Audio", () {}),
                const SizedBox(
                  width: 40,
                ),
                iconcreation(
                    Icons.location_pin, Colors.pink, "Location", () {}),
                const SizedBox(
                  width: 40,
                ),
                iconcreation(Icons.person, Colors.purple, "Contact", () {}),
              ],
            )
          ],
        ),
      ),
    );
  }

  Widget iconcreation(IconData icon, Color color, String text, Function onTap) {
    return InkWell(
      onTap: () {
        onTap();
      },
      child: Column(
        children: [
          CircleAvatar(
            radius: 30,
            backgroundColor: color,
            child: Icon(
              icon,
              size: 29,
              color: Colors.white,
            ),
          ),
          const SizedBox(),
          Text(
            text,
            style: const TextStyle(fontSize: 12),
          )
        ],
      ),
    );
  }

  // Widget emojiSelect() {
  //   return SizedBox(
  //       height: 250,
  //       child: EmojiPicker(
  //         textEditingController: _controller,
  //         onBackspacePressed: _onBackspacePressed,
  //         config: Config(
  //           columns: 7,
  //           // Issue: https://github.com/flutter/flutter/issues/28894
  //           emojiSizeMax: 32 *
  //               (foundation.defaultTargetPlatform == TargetPlatform.iOS
  //                   ? 1.30
  //                   : 1.0),
  //           verticalSpacing: 0,
  //           horizontalSpacing: 0,
  //           gridPadding: EdgeInsets.zero,
  //           initCategory: Category.RECENT,
  //           bgColor: const Color(0xFFF2F2F2),
  //           indicatorColor: Colors.blue,
  //           iconColor: Colors.grey,
  //           iconColorSelected: Colors.blue,
  //           backspaceColor: Colors.blue,
  //           skinToneDialogBgColor: Colors.white,
  //           skinToneIndicatorColor: Colors.grey,
  //           enableSkinTones: true,
  //           recentTabBehavior: RecentTabBehavior.RECENT,
  //           recentsLimit: 28,
  //           replaceEmojiOnLimitExceed: false,
  //           noRecents: const Text(
  //             'No Recents',
  //             style: TextStyle(fontSize: 20, color: Colors.black26),
  //             textAlign: TextAlign.center,
  //           ),
  //           loadingIndicator: const SizedBox.shrink(),
  //           tabIndicatorAnimDuration: kTabScrollDuration,
  //           categoryIcons: const CategoryIcons(),
  //           buttonMode: ButtonMode.MATERIAL,
  //           checkPlatformCompatibility: true,
  //         ),
  //       ));
  // }
}
